var express = require("express");
var router = express.Router();


var bodyParser = require("body-parser");
var urlencodedParser = bodyParser.urlencoded({ extended: false });


var user = require("../model/user");
var essay = require("../model/essay");


router.get("/", urlencodedParser, function(req, res) {

    essay
        .find({})
        .populate("user")
        .exec(function(err, docs) {
            res.render("index", { essays: docs, isAuth: req.isAuthenticated() });
        });
});

router.get("/main/:userId", urlencodedParser, function(req, res) {
    var userId = req.params.userId;
    user.findById(userId).exec(function(err, doc) {
        essay.find({ user: userId }).exec(function(err, docs) {
            res.render("main", { essays: docs, user: doc, isAuth: req.isAuthenticated() });
        });
    });

});

router.get("/essay/:essayId", urlencodedParser, function(req, res) {
    var essayId = req.params.essayId;
    essay
        .findById(essayId)
        .populate("comments.commentUser")
        .exec(function(err, doc) {
            res.render("essay", { essay: doc, isAuth: req.isAuthenticated() });
        });

});



module.exports = router;